package com.intexh.quickandroid.module.chat.ui.messageItemView;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.intexh.quickandroid.R;
import com.intexh.quickandroid.module.chat.ChatHelper;
import com.intexh.quickandroid.module.chat.ChatManager.EasemobManager;
import com.intexh.quickandroid.module.chat.bean.ChatMessage;
import com.intexh.quickandroid.module.chat.util.DateUtil;
import com.intexh.quickandroid.utils.GsonUtils;
import com.intexh.quickandroid.utils.ValidateUtils;
import com.intexh.quickandroid.utils.glide.GlideHelper;

import org.json.JSONException;
import org.json.JSONObject;


/**
 * Created by engine on 14-1-9.
 */
public abstract class AbsChatItem extends LinearLayout {
    protected ChatMessage mMessage;
    protected boolean mNeedTime = false;
    protected Context mContext;
    private EMMessage message;
    private ImageView failImageView;
    private ProgressBar progressBar;
    private RelativeLayout statusLayout;


    public AbsChatItem(Context context) {
        super(context);
        this.mContext = context;
    }

    public AbsChatItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }

    protected boolean needTime() {
        return mNeedTime;
    }

    protected void setTime(TextView textView, long time) {
        if (needTime()) {
            textView.setVisibility(VISIBLE);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) textView.getLayoutParams();

            params.setMargins(0, 0, 0, 0);
            textView.setText(DateUtil.chatTime(time));

        } else {
            textView.setVisibility(GONE);
        }
    }

    protected void setCommonLayout() {
        TextView timeTextView =  findViewById(R.id.time);
        setTime(timeTextView, mMessage.getCreate_time());
        ImageView groupMessageAvatarIv = (ImageView) findViewById(R.id.chat_group_message_avatar_iv);
        //如果是群聊 显示昵称
        if(mMessage.is_group()){
            TextView groupMessageNameTv = findViewById(R.id.chat_group_message_name_tv);
            groupMessageNameTv.setText(mMessage.getDisplay_name());
        }
        groupMessageAvatarIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // JumpUtils.JumpToUserHome(mContext,mMessage.getUid());
            }
        });
        String avatar;
        if (ChatHelper.getInstance().getUserInfo().getUid().equals(mMessage.getUid())){//针对我发送出去的
            avatar =  ChatHelper.getInstance().getUserInfo().getAvatar();
            statusLayout =  findViewById(R.id.statusLayout);
            failImageView =  findViewById(R.id.messageFail);
            progressBar =  findViewById(R.id.sendingProgress);
            //初始化状态显示 未发送的执行发送 发送失败的显示重新发送按钮
            switch (mMessage.getProgress()){
                case ChatMessage.PROGRESS_NO_SEND:  //未发送
                    sendChatMessage();
                case ChatMessage.PROGRESS_FAIL:     //发送失败
                    messageSendFail();
                    break;
                case ChatMessage.PROGRESS_COMPLETE: //发送完成 隐藏状态布局
                    messageSendComplete();
                    break;
            }
        }else{
            avatar =  mMessage.getAvatar();
        }
        if(ValidateUtils.isValidate(avatar)&&avatar.startsWith("http")){
            GlideHelper.INSTANCE.loadCircleImage(groupMessageAvatarIv,avatar);
        }else{
            GlideHelper.INSTANCE.loadCircleImage(groupMessageAvatarIv,R.mipmap.ic_launcher);
        }
    }


    private void messageSendFail() {
        post(() -> {
            failImageView.setVisibility(VISIBLE);
            progressBar.setVisibility(GONE);
            statusLayout.setOnClickListener(view -> resendMessage());
            requestLayout();
        });

    }
    private void messageSending() {
        post(() -> {
            failImageView.setVisibility(GONE);
            progressBar.setVisibility(VISIBLE);
            requestLayout();
        });
    }
    private void messageSendComplete() {
        post(() -> {
            statusLayout.setVisibility(GONE);
            requestLayout();
        });
    }

    private void resendMessage() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected()) {
        } else {
            post(() -> {
                mMessage.setCreate_time(System.currentTimeMillis());
                sendChatMessage();
            }) ;
        }
    }

    public void sendChatMessage() {
        if(mMessage.getProgress() == ChatMessage.PROGRESS_COMPLETE)return;  //已经发送完成的，不在继续发送
        mMessage.setProgress(ChatMessage.PROGRESS_SENDING);
        messageSending();
        mMessage.save();    //同步数据库
        switch (mMessage.getType()){
            case ChatMessage.TYPE_TEXT:
            case ChatMessage.TYPE_BLEND:
                message = EMMessage.createTxtSendMessage(mMessage.getContent(), mMessage.getEasemob_id());
                setCallBack();
                sendTextMessage(mMessage);
                break;
            case ChatMessage.TYPE_IMAGE:
                //imagePath为图片本地路径，false为不发送原图（默认超过100k的图片会压缩后发给对方），需要发送原图传true
                message = EMMessage.createImageSendMessage(mMessage.getLocalUrl(), false,  mMessage.getEasemob_id());
                setCallBack();
                sendImageMessage(mMessage);
                break;
            case ChatMessage.TYPE_VOICE:
                message = EMMessage.createVoiceSendMessage(mMessage.getLocalUrl(), mMessage.getVoiceLength(),  mMessage.getEasemob_id());
                setCallBack();
                sendVoiceMessage(mMessage);
                break;
        }
    }
    private void setCallBack() {
        try {
            // 发送消息
            message.setMessageStatusCallback(new EMCallBack() {
                @Override
                public void onSuccess() {
                    mMessage.setProgress(ChatMessage.PROGRESS_COMPLETE);
                    messageSendComplete();
                    mMessage.save();    //同步数据库
                }

                @Override
                public void onProgress(int arg0, String arg1) {
                }

                @Override
                public void onError(int arg0, String arg1) {
                    if (!EasemobManager.INSTANCE.isLogin()) {
                        mMessage.setProgress(ChatMessage.PROGRESS_FAIL);
                        messageSendFail();
                        mMessage.save();    //同步数据库
                        ChatHelper.getInstance().login(ChatHelper.getInstance().getUserInfo().getChat_id(),ChatHelper.getInstance().getUserInfo().getChat_pwd());
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            mMessage.setProgress(ChatMessage.PROGRESS_FAIL);
            messageSendFail();
            mMessage.save();    //同步数据库
        }
    }

    //文本信息
    public void sendTextMessage(ChatMessage chatMessage){
        try {
            if(chatMessage.is_group()) {
                message.setAttribute("em_apns_ext", (new JSONObject()).put("em_push_title", chatMessage.getDisplay_name()+chatMessage.getContent()));
                message.setAttribute("ext", GsonUtils.serializedToJson(chatMessage));
                message.setChatType(EMMessage.ChatType.GroupChat);
            }else {
                message.setAttribute("em_apns_ext", (new JSONObject()).put("em_push_title", chatMessage.getDisplay_name()+chatMessage.getContent()));
                message.setAttribute("ext", GsonUtils.serializedToJson(chatMessage));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        EMClient.getInstance().chatManager().sendMessage(message);
    }

    //语音信息
    public void sendVoiceMessage(ChatMessage chatMessage){
        try {
            if(chatMessage.is_group()) {
                message.setAttribute("ext", GsonUtils.serializedToJson(chatMessage));
                message.setAttribute("em_apns_ext", (new JSONObject()).put("em_push_title", chatMessage.getDisplay_name()+"[发来一段语音]"));
                message.setChatType(EMMessage.ChatType.GroupChat);
            }else {
                message.setAttribute("ext", GsonUtils.serializedToJson(chatMessage));
                message.setAttribute("em_apns_ext", (new JSONObject()).put("em_push_title", chatMessage.getDisplay_name()+"[发来一段语音]"));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        EMClient.getInstance().chatManager().sendMessage(message);
    }

    //图片信息
    public void sendImageMessage(ChatMessage chatMessage){
        try {
            if(chatMessage.is_group()) {
                message.setAttribute("ext", GsonUtils.serializedToJson(chatMessage));
                message.setAttribute("em_apns_ext", (new JSONObject()).put("em_push_title", chatMessage.getDisplay_name()+"[发来一张图片]"));
                message.setChatType(EMMessage.ChatType.GroupChat);
            }else {
                message.setAttribute("ext", GsonUtils.serializedToJson(chatMessage));
                message.setAttribute("em_apns_ext", (new JSONObject()).put("em_push_title", chatMessage.getDisplay_name()+"[发来一张图片]"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        EMClient.getInstance().chatManager().sendMessage(message);
    }


}
